﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace MicroMvvm
{
    /// <summary>
    /// 实现事件到命令的传递
    /// </summary>
    public class RelayEvent : TriggerAction<DependencyObject>
    {

        // Using a DependencyProperty as the backing store for MsgName.  
        // This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(ICommand), typeof(RelayEvent), new PropertyMetadata(null));

        // Using a DependencyProperty as the backing store for CommandParateter.  
        // This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CommandParateterProperty =
            DependencyProperty.Register("CommandParateter", typeof(object), typeof(RelayEvent), new PropertyMetadata(null));

        /// <summary>
        /// 事件要绑定的命令
        /// </summary>
        public ICommand Command
        {
            get => (ICommand) GetValue(CommandProperty);
            set => SetValue(CommandProperty, value);
        }

        /// <summary>
        /// 绑定命令的参数，保持为空就是事件的系统参数
        /// </summary>
        public object CommandParateter
        {
            get => GetValue(CommandParateterProperty);
            set => SetValue(CommandParateterProperty, value);
        }

        //执行事件
        protected override void Invoke(object parameter)
        {
            if (CommandParateter != null)
            {
                parameter = CommandParateter;
            }
            var cmd = Command;
            cmd?.Execute(parameter);
        }
    }
}
